package com.whq.thrift.api.web.admin.controller;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.whq.common.StringUtil;
import com.whq.thrift.api.common.spring.ReloadableConfManager;
import com.whq.thrift.api.web.admin.util.LoginUtil;

/**
 * 登录
 * @author whq-mac
 *
 */

@Controller
@Scope("prototype")
public class LoginController {
	@Autowired
	private ReloadableConfManager reloadableConfManager;
	
	@RequestMapping(value="login/index")
	public String index(Model model,
	        HttpServletRequest request) {
		return "login/index";
	}
	
	@RequestMapping(value="login/login")
	public String login(@RequestParam(value = "loginName", required = true) String loginName,
			@RequestParam(value = "loginPwd", required = true) String loginPwd,
			Model model,
	        HttpServletRequest request,
	        HttpServletResponse response
	        ) {
		model.addAttribute("loginName", loginName);
		
		if (StringUtil.isBlank(loginName)) {
			model.addAttribute("errMsg_loginName", "请输入登录名");
			return "login/index";
		}
		
		if (StringUtil.isBlank(loginPwd)) {
			model.addAttribute("errMsg_loginPwd", "请输入密码");
			return "login/index";
		}
		
		String realLoginName = reloadableConfManager.getPropertyValue("admin.login.name", null, "");
		String realLoginPwdPrefix = reloadableConfManager.getPropertyValue("admin.login.pwd.prefix", null, "");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
		String realLoginPwd = realLoginPwdPrefix + sdf.format(new Date());
		
		if (!loginName.equals(realLoginName)) {
			model.addAttribute("errMsg_loginName", "登录名不存在");
			return "login/index";
		}
		
		if (!loginPwd.equals(realLoginPwd)) {
			model.addAttribute("errMsg_loginName", "密码错误");
			return "login/index";
		}
		
		LoginUtil.saveLoginTicket(request, response, loginName);
		return "redirect:../index/index.do";
	}
	
	@RequestMapping(value="login/logout")
	public String logout(Model model,
	        HttpServletRequest request,
	        HttpServletResponse response) {
		LoginUtil.clearLoginInfo(request, response);
		return "redirect:index.do";
	}
}

